

#ifdef TARGETLINUX
#include "api.h"
#include <sys/time.h>
#include <signal.h>

pthread_mutexattr_t mutant;
pthread_attr_t that;  


HMTX TSmtx;
HMTX CSmtx;
HMTX PSmtx;
ULONG timestart;

clock_t clock()
{
  struct timeval x;
  int success=gettimeofday(&x,0);
  if (success==0){
    if (timestart==0){
      timestart=x.tv_sec;
      return 0;
    }else{
      x.tv_sec-=timestart;
      return (clock_t)(x.tv_sec*1000+x.tv_usec/1000);
    }
  }else
    return 0;
}

int memicmp(char* a,char* b,int n)
{
  for(int i=0;i<n;++i){
    if(a[i]!=b[i]){
      char c=a[i]|0x20;
      if(c>='a' && c<='z'){
        char d=b[i]|0x20;
        if(c==d)
	  continue;
        else
          if(d>='a' && d<='z')
            return c-d;
      }
      return(a[i]-b[i]);
    }
  }
  return 0;
}

sem_t* vents[512];
int clocks[512];


int sus=0;

void postEvents()
{
	pthread_mutex_lock(PSmtx);
	for(int i=0;i<sus;++i){
		clocks[i]--;
		if(clocks[i]<=0)			
			sem_post(vents[i]);
	}
	pthread_mutex_unlock(PSmtx);
}



void setClock(sem_t* h,ULONG n)
{
  if(n!=INFINITE){
   int i=0;
   pthread_mutex_lock(PSmtx);
   for(;i<sus;++i)
    if (vents[i]==h)
      break;
   vents[i]=h;
   clocks[i]=(n/1000)+1;
   if(i==sus)
    sus++;
   pthread_mutex_unlock(PSmtx);
  }
}


void clearClock(sem_t* h)
{
	int i=0;
	pthread_mutex_lock(PSmtx);
	for(;i<sus;++i){
		if (vents[i]==h){
			sus--;
			break;
		}
	}
	if(i<sus){
		vents[i]=vents[sus];
		clocks[i]=clocks[sus];
	}
	pthread_mutex_unlock(PSmtx);
}

extern int shutcaravan;
void catch_int(int signum)
{
	shutcaravan=1;
	SleepMilSec(100000);
	exit(0);
}

void initLinuxApi()
{
 clock();
 pthread_mutexattr_init(&mutant); 
 pthread_mutexattr_settype(&mutant,PTHREAD_MUTEX_RECURSIVE_NP);
 pthread_attr_init(&that); 
 pthread_attr_setdetachstate(&that,PTHREAD_CREATE_DETACHED);
 TSmtx=(pthread_mutex_t*) new char[sizeof(pthread_mutex_t)];
 pthread_mutex_init(TSmtx,&mutant);
 CSmtx=(pthread_mutex_t*) new char[sizeof(pthread_mutex_t)];
 pthread_mutex_init(CSmtx,&mutant);
 PSmtx=(pthread_mutex_t*) new char[sizeof(pthread_mutex_t)];
 pthread_mutex_init(PSmtx,&mutant);
 signal(SIGPIPE,SIG_IGN);
 signal(SIGSEGV,catch_int);
}

#endif



















